import asyncio
import re

from playwright.async_api import Page


class OkxAutoScriptPage:
    def __init__(self, page: Page):
        self.page = page

    async def run(self):
        await self.OkxAutoScriptHandle()

    async def getBodyContent(self):
        return await self.page.evaluate('document.body.innerHTML')

    async def getRouter(self):
        await asyncio.sleep(1)
        bodyContent = await self.getBodyContent()
        print(bodyContent)
        if re.search(r"请输入密码", bodyContent):
            return 'login'
        if re.search(r"允许当前 DApp 连接你的插件钱包", bodyContent):
            return 'connected'
        return None

    async def OkxAutoScriptHandle(self):
        while True:
            try:
                router = await self.getRouter()
                print(router)
                if router == 'connected':
                    await self.connectedHandle()
                elif router == 'login':
                    await self.loginHandle()
            except Exception as e:
                print(e)

    async def loginHandle(self):
        await self.page.fill('//input[@placeholder="请输入密码"]', "Liu123456")
        await self.page.click('//button[@data-testid="okd-button"]')

    async def connectedHandle(self):
        await self.page.click('//div[text()="连接"]')
